1688D - The Enchanted Forest - CodeForces Solution


greedy implementation math *1600

Please click on ads to support us..

Python Code:

x = int(input())
def cal(n,m,arr):
    if m >= n:
        t = sum(arr) + n*(m-1) - (n-1)*n//2
        return t
    t = sum(arr[:m])
    k = t
    for i in range(n-m):
        k -= arr[i]
        k += arr[i+m]
        t = max(t,k)
    return t + m*(m-1) - m*(m-1)//2
for jj in range(x):
    n,m = [int(i) for i in input().split(' ')]
    arr = [int(i) for i in input().split(' ')]
    print(cal(n,m,arr))

C++ Code:

#include <bits/stdc++.h>
#define int long long

using namespace std;

typedef long long ll;

int lowbit(int x)
{
    return x & -x;
}

// int query(vector<int> tree, int node, int ns, int ne, int qs, int qe)
// {
//     int ans = 0;
//     if (qe < ns || qs > ne) return ans;
//     if (qe <= ns && qs >= ne) return tree[node];


// }

void solve()
{
    int n, k;
    cin >> n >> k;
    vector<int> a(n);
    for (int i = 0; i < n; i ++ ) cin >> a[i];
    vector<int> prevfixSum(n + 1, 0);
    for (int i = 1; i <= n; i ++ ) prevfixSum[i] = prevfixSum[i - 1] + a[i - 1];
    int ans = 0;


    if (k < n){
        ans = prevfixSum[k];
        for (int i = k + 1; i <= n; i ++ ) ans = max(ans, prevfixSum[i] - prevfixSum[i - k]);
        cout << ans + k * (k - 1) / 2 << endl;
        return;
    }

    cout << prevfixSum[n] + (k - 1 + k - n) * n / 2 << endl;
}

signed main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);

    int _T;
    cin >> _T;
    while (_T -- )
    {
        solve();
    }

    return 0;
}


Comments

Submit
0 Comments
More Questions

36. Valid Sudoku
557. Reverse Words in a String III
566. Reshape the Matrix
167. Two Sum II - Input array is sorted
387. First Unique Character in a String
383. Ransom Note
242. Valid Anagram
141. Linked List Cycle
21. Merge Two Sorted Lists
203. Remove Linked List Elements
733. Flood Fill
206. Reverse Linked List
83. Remove Duplicates from Sorted List
116. Populating Next Right Pointers in Each Node
145. Binary Tree Postorder Traversal
94. Binary Tree Inorder Traversal
101. Symmetric Tree
77. Combinations
46. Permutations
226. Invert Binary Tree
112. Path Sum
1556A - A Variety of Operations
136. Single Number
169. Majority Element
119. Pascal's Triangle II
409. Longest Palindrome
1574A - Regular Bracket Sequences
1574B - Combinatorics Homework
1567A - Domino Disaster
1593A - Elections